package m2;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer {
    public static void main(String[] args) throws Exception {
        //连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Connection con = f.newConnection();
        Channel c = con.createChannel();//通信通道
        //队列
        c.queueDeclare("task_queue", true, false, false, null);
        //创建回调对象 DeliverCallback,CancelCallback
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                System.out.println("收到:"+msg);
                //遍历字符串每个点字符暂停1s
                for (int i=0;i<msg.length();i++){
                    if ('.' == msg.charAt(i)){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                //在这里手动发送回执
                c.basicAck(message.getEnvelope().getDeliveryTag(),false);//回执,是否把之前接收的所有消息一起确认
                System.out.println("---消息处理结束---");

            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };

        //每次只处理一条消息,处理完成之前不会抓取下一条->只有手动ack有效
        c.basicQos(1);
        //消费数据
        c.basicConsume("task_queue", false,deliverCallback,cancelCallback);
        //第二个参数:true指的是自动ack,服务器发送消息时,自动确认消息,删除消息
        //false指的是手动确认ack,服务器发送后将消息缓存,只有收到回执之后才会删除消息,否则不会删除,回滚

    }
}
